/*
 * Copyright 2016 Yan Zhenjie
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.rhythms.swiperecyclerview;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rhythms.R;
import com.rhythms.swiperecyclerview.adapter.RhythmsAdapterEditSpinner;
import com.rhythms.swiperecyclerview.bean.RhythmsIntStrBean;
import com.rhythms.swiperecyclerview.bean.RhythmsItemBean;
import com.rhythms.swiperecyclerview.listener.OnItemPlayListener;
import com.rhythms.swiperecyclerview.utils.RhythmsStaticConstants;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Yan Zhenjie on 2016/8/3.
 */
public class RhythmsActEdit extends AppCompatActivity {

    @BindView(R.id.rhythms_id_sp_start_sound_id)
    Spinner rhythmsIdSpStartSoundId;
    @BindView(R.id.rhythms_id_sp_rate_sound_id)
    Spinner rhythmsIdSpRateSoundId;
    @BindView(R.id.rhythms_id_sp_period)
    Spinner rhythmsIdSpPeriod;
    @BindView(R.id.rhythms_id_sp_times)
    Spinner rhythmsIdSpTimes;
    @BindView(R.id.rhythms_id_sp_cycles)
    Spinner rhythmsIdSpCycles;
    @BindView(R.id.rhythms_id_sp_default)
    Spinner rhythmsIdSpDefault;
    @BindView(R.id.rhythms_id_tv_start_sound_id)
    TextView rhythmsIdTvStartSoundId;
    @BindView(R.id.rhythms_id_tv_rate_sound_id)
    TextView rhythmsIdTvRateSoundId;
    @BindView(R.id.rhythms_id_tv_period)
    TextView rhythmsIdTvPeriod;
    @BindView(R.id.rhythms_id_tv_times)
    TextView rhythmsIdTvTimes;
    @BindView(R.id.rhythms_id_tv_cycles)
    TextView rhythmsIdTvCycles;
    @BindView(R.id.rhythms_id_text_main)
    LinearLayout rhythmsIdTextMain;
    @BindView(R.id.rhythms_id_spinner_main)
    LinearLayout rhythmsIdSpinnerMain;
    @BindView(R.id.rhythms_id_et_remarks)
    EditText rhythmsIdEtRemarks;
    private Activity mContext;
    private Unbinder unbinder;
    private String itemJsonData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rhythms_act_edit);
        unbinder = ButterKnife.bind(this);
        ButterKnife.bind(this);
        mContext = this;
//        int[] permissionImgIds = mContext.getResources().getIntArray(R.array.rhythms_array_cycles_int);

        testSpinnerSelf();
    }

    //RhythmsIntStrBean就不贴出来了

    /**
     * Spinner完全自定义UI和绑定数据
     */
    private void testSpinnerSelf() {
        // 解析数据
        String json = getRawJson();
        Log.i("ddkkkdddkk", "json:== " + json);
        if (json != null) {
            Gson gson = new Gson();
            Type type = new TypeToken<Map<String, Map<String, Integer>>>() {
            }.getType();
            Map<String, Map<String, Integer>> configInfos = gson.fromJson(json, type);
            // 1. entrySet遍历，在键和值都需要时使用（最常用）
//            for (Map.Entry<String, Map<String, Integer>> entry : configInfos.entrySet()) {
//                Log.i("ddkkkdddkk", "第一层key = " + entry.getKey());
//                for (Map.Entry<String, Integer> entry2 : entry.getValue().entrySet()) {
//                    Log.i("ddkkkdddkk", "第二层key = " + entry2.getKey() + ", value = " + entry2.getValue());
//                }
//            }
            Map<String, Integer> periodMap = configInfos.get("rhyperiod");
            Map<String, Integer> timesMap = configInfos.get("rhytimes");
            Map<String, Integer> cyclesMap = configInfos.get("rhycycles");
            Map<String, Integer> defaultMap = configInfos.get("rhydefault");

            initSpinner(rhythmsIdSpPeriod, periodMap);
            initSpinner(rhythmsIdSpTimes, timesMap);
            initSpinner(rhythmsIdSpCycles, cyclesMap);
            initSpinner(rhythmsIdSpDefault, defaultMap);
            rhythmsIdSpDefault.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                    Log.i("ddkkkdddkk", "AdapterView pos= " + pos);
                    Log.i("ddkkkdddkk", "AdapterView id= " + id);
                    if (parent.getSelectedItem() instanceof RhythmsIntStrBean) {
                        RhythmsIntStrBean intStrBean = (RhythmsIntStrBean) parent.getSelectedItem();
                        Log.i("ddkkkdddkk", "AdapterView intStrBean= " + intStrBean.getRhyName());
                        if (intStrBean.getRhyData() == 0) {
                            rhythmsIdTextMain.setVisibility(View.GONE);
                            rhythmsIdSpinnerMain.setVisibility(View.VISIBLE);
                        } else {
                            rhythmsIdTextMain.setVisibility(View.VISIBLE);
                            rhythmsIdSpinnerMain.setVisibility(View.GONE);
                            if (intStrBean.getRhyData() == 1) {
                                itemJsonData = setDefaultData(22, 25, 60, 10, 3, intStrBean.getRhyName(), "30秒休息");
                            } else if (intStrBean.getRhyData() == 2) {
                                itemJsonData = setDefaultData(21, 24, 60, 20, 3, intStrBean.getRhyName(), "60秒休息");
                            } else if (intStrBean.getRhyData() == 3) {
                                itemJsonData = setDefaultData(6, 27, 180, 180, 3, intStrBean.getRhyName(), "3分钟跑步");
                            } else if (intStrBean.getRhyData() == 4) {
                                itemJsonData = setDefaultData(17, 4, 120, 120, 3, intStrBean.getRhyName(), "3分钟瑜伽");
                            } else if (intStrBean.getRhyData() == 5) {
                                itemJsonData = setDefaultData(20, 2, 30, 30, 8, intStrBean.getRhyName(), "板桥+卷腹");
                            } else if (intStrBean.getRhyData() == 6) {
                                itemJsonData = setDefaultData(19, 13, 20, 50, 2, intStrBean.getRhyName(), "俯卧or深蹲");
                            } else if (intStrBean.getRhyData() == 7) {
                                itemJsonData = setDefaultData(21, 16, 60, 30, 10, intStrBean.getRhyName(), "5分钟休息");
                            }
                        }
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                }
            });

            List<RhythmsIntStrBean> intStrBeanList = new ArrayList<>();
            for (int i = 0; i < RhythmsStaticConstants.SOUND_RAW_IDS.length; i++) {
                RhythmsIntStrBean intStrBean = new RhythmsIntStrBean();
                intStrBean.setRhyPosition(i);
                intStrBean.setRhyName("sound_0" + i);
                intStrBean.setRhyData(i);
                intStrBeanList.add(intStrBean);
            }
            RhythmsAdapterEditSpinner adapter = new RhythmsAdapterEditSpinner(mContext, intStrBeanList);
            rhythmsIdSpStartSoundId.setAdapter(adapter);
            rhythmsIdSpRateSoundId.setAdapter(adapter);
            Intent intent = getIntent();
            Bundle bundle = intent.getExtras();
            Log.i("ddkkkdddkk", "bundle:== " + bundle);
            if (bundle != null) {
                itemJsonData = bundle.getString("itemDataStr");
                Log.i("ddkkkdddkk", "bundle-itemJsonData:== " + itemJsonData);
                gson = new Gson();
                type = new TypeToken<RhythmsItemBean>() {
                }.getType();
                RhythmsItemBean rhythmsItemBean = gson.fromJson(itemJsonData, type);
//                RhythmsAdapterEditSpinner editSpinner = (RhythmsAdapterEditSpinner)rhythmsIdSpStartSoundId.getAdapter();
//                for (int i = 0; i < editSpinner.getRhythmsIntStrBeanList().size(); i++) {
//                    if(editSpinner.getRhythmsIntStrBeanList().get(i).getRhyName().equals(rhythmsItemBean.getRhyStartSound().getRhyName())){
//                        rhythmsIdSpStartSoundId.setSelection(i);
//                    }
//                }
                setSecondEditData(rhythmsIdSpStartSoundId, rhythmsItemBean.getRhyStartSound());
                setSecondEditData(rhythmsIdSpRateSoundId, rhythmsItemBean.getRhyRateSound());
                setSecondEditData(rhythmsIdSpPeriod, rhythmsItemBean.getRhyPeriod());
                setSecondEditData(rhythmsIdSpTimes, rhythmsItemBean.getRhyTimes());
                setSecondEditData(rhythmsIdSpCycles, rhythmsItemBean.getRhyCycles());
                rhythmsIdEtRemarks.setText(rhythmsItemBean.getRhyItemShow().getRhyRemarks());
            } else {
                // 设置默认选项
                rhythmsIdSpStartSoundId.setSelection(21);
                rhythmsIdSpRateSoundId.setSelection(11);
                rhythmsIdSpPeriod.setSelection(2);
                rhythmsIdSpTimes.setSelection(3);
                rhythmsIdSpCycles.setSelection(2);
                itemJsonData = getCustomData();
                Log.i("ddkkkdddkk", "bundle-itemJsonData2222:== " + itemJsonData);
            }
        }
//        rhythmsIdSpPeriod.getSelectedItem();
    }

    private void setSecondEditData(Spinner spinner, RhythmsIntStrBean rhythmsIntStrBean) {
        RhythmsAdapterEditSpinner editSpinner = (RhythmsAdapterEditSpinner) spinner.getAdapter();
        for (int i = 0; i < editSpinner.getRhythmsIntStrBeanList().size(); i++) {
            if (editSpinner.getRhythmsIntStrBeanList().get(i).getRhyData() == rhythmsIntStrBean.getRhyData()) {
                spinner.setSelection(i);
            }
        }
    }

    private String setDefaultData(long sSound, long rSound, long period, long times, long cycles, String name, String remarks) {
        RhythmsItemBean rhythmsItemBean = new RhythmsItemBean();
        RhythmsIntStrBean intStrBeanSSound = new RhythmsIntStrBean();
        RhythmsIntStrBean intStrBeanRSound = new RhythmsIntStrBean();
        RhythmsIntStrBean intStrBeanPeriod = new RhythmsIntStrBean();
        RhythmsIntStrBean intStrBeanTimes = new RhythmsIntStrBean();
        RhythmsIntStrBean intStrBeanCycles = new RhythmsIntStrBean();
        RhythmsIntStrBean intStrBeanShow = new RhythmsIntStrBean();
        // 开始音
        intStrBeanSSound.setRhyName("start_" + sSound);
        intStrBeanSSound.setRhyData(sSound);
        rhythmsItemBean.setRhyStartSound(intStrBeanSSound);
        // 间隔音
        intStrBeanRSound.setRhyName("rate_" + rSound);
        intStrBeanRSound.setRhyData(rSound);
        rhythmsItemBean.setRhyRateSound(intStrBeanRSound);
        // 间隔时间
        intStrBeanPeriod.setRhyName(period + "MS");
        intStrBeanPeriod.setRhyData(period);
        rhythmsItemBean.setRhyPeriod(intStrBeanPeriod);
        // 次数
        intStrBeanTimes.setRhyName(times + "b");
        intStrBeanTimes.setRhyData(times);
        rhythmsItemBean.setRhyTimes(intStrBeanTimes);
        // 循环
        intStrBeanCycles.setRhyName(cycles + "g");
        intStrBeanCycles.setRhyData(cycles);
        rhythmsItemBean.setRhyCycles(intStrBeanCycles);
        // 名称
        intStrBeanShow.setRhyName(name);
        intStrBeanShow.setRhyRemarks(remarks);
        rhythmsItemBean.setRhyItemShow(intStrBeanShow);
        Gson gson = new Gson();
        return gson.toJson(rhythmsItemBean);
    }

    private String getCustomData() {
        String showName = "";
        RhythmsItemBean rhythmsItemBean = new RhythmsItemBean();
        RhythmsIntStrBean intStrBean = new RhythmsIntStrBean();
        if (rhythmsIdSpPeriod.getSelectedItem() instanceof RhythmsIntStrBean) {
            intStrBean = (RhythmsIntStrBean) rhythmsIdSpPeriod.getSelectedItem();
            rhythmsItemBean.setRhyPeriod(intStrBean);
            showName += intStrBean.getRhyName();
        }
        if (rhythmsIdSpTimes.getSelectedItem() instanceof RhythmsIntStrBean) {
            intStrBean = (RhythmsIntStrBean) rhythmsIdSpTimes.getSelectedItem();
            rhythmsItemBean.setRhyTimes(intStrBean);
            showName += intStrBean.getRhyName();
        }
        if (rhythmsIdSpCycles.getSelectedItem() instanceof RhythmsIntStrBean) {
            intStrBean = (RhythmsIntStrBean) rhythmsIdSpCycles.getSelectedItem();
            rhythmsItemBean.setRhyCycles(intStrBean);
            showName += intStrBean.getRhyName();
        }
        if (rhythmsIdSpStartSoundId.getSelectedItem() instanceof RhythmsIntStrBean) {
            intStrBean = (RhythmsIntStrBean) rhythmsIdSpStartSoundId.getSelectedItem();
            rhythmsItemBean.setRhyStartSound(intStrBean);
//            showName += intStrBean.getRhyName();
        }
        if (rhythmsIdSpRateSoundId.getSelectedItem() instanceof RhythmsIntStrBean) {
            intStrBean = (RhythmsIntStrBean) rhythmsIdSpRateSoundId.getSelectedItem();
            rhythmsItemBean.setRhyRateSound(intStrBean);
//            showName += intStrBean.getRhyName();
        }
        RhythmsIntStrBean intStrBean2 = new RhythmsIntStrBean();
        intStrBean2.setRhyName(showName);
        intStrBean2.setRhyRemarks(rhythmsIdEtRemarks.getText().toString());
        rhythmsItemBean.setRhyItemShow(intStrBean2);

        Gson gson = new Gson();
        return gson.toJson(rhythmsItemBean);
    }

    private void initSpinner(Spinner spinner, Map<String, Integer> integerMap) {
        List<RhythmsIntStrBean> intStrBeanList = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : integerMap.entrySet()) {
            Log.i("ddkkkdddkk", "第二层key = " + entry.getKey() + ", value = " + entry.getValue());
            RhythmsIntStrBean intStrBean = new RhythmsIntStrBean();
            intStrBean.setRhyName(entry.getKey());
            intStrBean.setRhyData(entry.getValue());
            intStrBeanList.add(intStrBean);
        }
        RhythmsAdapterEditSpinner adapter = new RhythmsAdapterEditSpinner(mContext, intStrBeanList);
        spinner.setAdapter(adapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除绑定
        unbinder.unbind();
    }

    private String getRawJson() {
        //将json文件(存放在本地的res/raw)读取到buffer数组中
        InputStream is = this.getResources().openRawResource(R.raw.packconfig);
        try {
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            //  将字符数组转换为UTF-8编码的字符串
            return new String(buffer, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @OnClick({R.id.rhythms_id_edit_back, R.id.rhythms_id_edit_play, R.id.rhythms_id_edit_stop, R.id.rhythms_id_edit_done})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rhythms_id_edit_back:
                finish();
                break;
            case R.id.rhythms_id_edit_stop:
                RhythmsPlaySound.getInstance().stopOneCycles();
                break;
            case R.id.rhythms_id_edit_done:
                if (rhythmsIdSpDefault.getSelectedItem() instanceof RhythmsIntStrBean) {
                    RhythmsIntStrBean intStrBean = (RhythmsIntStrBean) rhythmsIdSpDefault.getSelectedItem();
                    Log.i("ddkkkdddkk", "AdapterView intStrBean= " + intStrBean.getRhyName());
                    Log.i("ddkkkdddkk", "AdapterView getRhyData= " + intStrBean.getRhyData());
                    if (intStrBean.getRhyData() == 0) {
                        itemJsonData = getCustomData();
                    }
                }
                Log.i("ddkkkdddkk", "AdapterView-itemJsonData:== " + itemJsonData);
                Intent intent = new Intent();
                intent.putExtra("RhythmsItemBean", itemJsonData);
                setResult(3, intent);
                RhythmsPlaySound.getInstance().stopOneCycles();
                finish();
                break;
            case R.id.rhythms_id_edit_play:
                Gson gson = new Gson();
                Type type = new TypeToken<RhythmsItemBean>() {
                }.getType();
                RhythmsItemBean rhythmsItemBean = gson.fromJson(getCustomData(), type);
                if (rhythmsItemBean != null) {
                    List<RhythmsItemBean> mRhythmsItemBeanList = new ArrayList<>();
                    rhythmsItemBean.setRhySelect(true);
                    mRhythmsItemBeanList.add(rhythmsItemBean);
                    RhythmsPlaySound.getInstance().startOneCycles(0, mRhythmsItemBeanList, onItemPlayListener);
                }
                break;
        }
    }

    private OnItemPlayListener onItemPlayListener = new OnItemPlayListener() {
        @Override
        public void onItemPlay(int position) {
        }
    };
}